<?php
namespace Admin\Controller;
use Common\Controller\BackendController;

// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------

class PrivilegeController extends BackendController {
    public function _initialize() {
        parent::_initialize(); 
        $this -> item_mod = M('Items');
        $api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
        $this->_tbconfig = unserialize($api_config);
    }
    public function index() {
        $itk_session_time=C('itk_session_time');
        $this->assign('itk_session_time',date('Y-m-d',$itk_session_time));
        $this->assign('itk_session_etime',date('Y-m-d',$itk_session_time+30*3600*24));
        $this->display();
    }
    
    
    public function setting() {
        if (IS_POST) {
            $cate_id	= $this->_post('cate_id', 'trim',0);
            $privilege_type		= $this->_post("privilege_type" , "trim",0);
            $fid		= $this->_post("fid" , "trim");
            $eid		= $this->_post("eid" , "trim");

//             if (!$cate_id) {
//                 $this->ajaxReturn(0, "入库分类必须选择!");
//             }
            
            if( $this->_tbconfig =='')
            	$this->ajaxReturn(0, "请正确配置爱淘客开放平台接口!");
            
			//把采集信息写入缓存
            F("quancaiji_setting" , array(
                "cate_id" => $cate_id,
                "privilege_type" => $privilege_type,
                "fid" => $fid,
            	"eid" => $eid,
            ));
            $this->collect();
        }
    }
    
    public function collect() {
    	
        if (false === $quancaiji_setting = F('quancaiji_setting')) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }

        $taodianjin = C('itk_taojindian_html');
        if (strpos($taodianjin, "text/javascript")) {
        	$pid = get_word($taodianjin, 'pid: "' , '"');
        } else {
        	$pid = $taodianjin;
        }
        if (!$pid) {
        	$this->ajaxReturn(0, '请设置淘点金后采集！否则无佣金');
        }
        
        $user_session=C('itk_user_session');
        if(!$user_session){
            $this->ajaxReturn(0, '请先点击登陆淘宝账户获取授权session');
        }
        
		$where['coupon_end_time']= array('EGT',time());						//只批量处理时间正常的优惠券
		$where['status'] ='underway';
		if($quancaiji_setting['cate_id']!=0)
		    $where['cate_id'] =$quancaiji_setting['cate_id'];
		if($quancaiji_setting['privilege_type']==0)
		    $where['ding'] = 0;
		
		$where['isq']=1;
		$fid = $quancaiji_setting['fid'];
		$eid = $quancaiji_setting['eid'];
		if ($fid && $eid) {
		    if($eid !=0)
		        $where['id'] = array(array('egt', $fid), array('elt', $eid));
		}	
		$p = $this->_get('p', 'intval', 1);
		
		$allcount = $this ->item_mod->where($where)->count('id');
		if ($allcount==0) {
		    $this->ajaxReturn(0, '已全部申请完成,无需再申请');
		}
		if($p==1){
		    F('allcount',$allcount);
		}
		
		$res = $this->item_mod->where($where)->order("id asc")->limit(1)->select();
		if (!$res) {
		    $this->ajaxReturn(0, '已全部申请完成,无需再申请');
		}	
		$activityId= $this->getActivityId($res[0]['quanurl']);
        $tb_top = $this->_get_top();
        $req = $tb_top->load_api('ItaokePrivilegeGetRequest');
        $req->setPid($pid);
        $req->putOtherTextParam('session',$user_session);				   // 设置采集数据分类ID
        $req->putOtherTextParam('item_id',$res[0]['num_iid']);				// 设置最小佣金
        $req->putOtherTextParam('activityId',$activityId);
        $req->putOtherTextParam('me','');
        $resp = (array)$tb_top->execute($req);

        if($resp['status'] != '0000')
        {
        	$this->ajaxReturn(0, $resp['msg']);
        }
        else
        {
            $trueData=$resp['data'];
            if($trueData['status']==-1){
                $this->ajaxReturn(0, $trueData['msg']);
            }
        	if ($p == 1) {
        		$totalcoll = 0;
        	} else {
        		$totalcoll = F("totalcoll");
        	}
        	

			$data['click_url'] = $trueData['data'];
			$data['ding']=1;
			$this->item_mod->where(array('id'=>$res[0]['id']))->save($data);

			$totalcoll++;
        	F("totalcoll" , $totalcoll);
        	$this->assign('p', $p);								// 采集当前页数
        	$this->assign("totalcoll" , $totalcoll);				// 总个数
        	$this->assign("allcount" , $allcount);
        	
        	$_resp = $this->fetch("info");
        	$this->ajaxReturn(1, '', $_resp);
        }
    }
    
    private function _ajax_tb_publish_insert($item) {
      return D('Items')->ajax_itk_publish($item);
    }

    private function _get_top() {
    	vendor('Itaoke.TopClient');
    	vendor('Itaoke.RequestCheckUtil');
    	vendor('Itaoke.Logger');
    	$top = new \TopClient;
    	$top->appkey = $this->_tbconfig['app_key'];
    	$top->secretKey = $this->_tbconfig['app_secret'];
    	return $top;
    }
    
    public function getActivityId($url){
        $url=htmlspecialchars_decode($url);
        $geturl = parse_url($url);
        $params = convertUrlQuery($geturl['query']);
        
        $activityId = $params['activityId'] == '' ? $params['activity_id']:$params['activityId'];

        return $activityId;
    }
} 
?>
